package com.sywb.chuangyebao.view.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.Channel;

import org.bining.footstone.adapter.BaseRecyclerMultiItemAdapter;
import org.bining.footstone.adapter.ViewHolderHelper;
import org.bining.footstone.adapter.listener.OnItemChildClickListener;
import org.bining.footstone.log.Logger;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 首页频道配置
 */
public class ChannelDialogFragment extends DialogFragment {

    public static String DATA_SELECTED = "dataSelected";
    public static String DATA_UNSELECTED = "dataUnselected";

    @BindView(R.id.activity_channel)
    LinearLayout activityChannel;
    @BindView(R.id.actionbar)
    RelativeLayout actionbar;
    @BindView(R.id.actionbar_back)
    ImageView actionbarBack;
    @BindView(R.id.actionbar_title)
    TextView actionbarTitle;
    @BindView(R.id.channel_recyclerView)
    RecyclerView mRecyclerView;

    private Unbinder unbinder;

    private ChannelAdapter mAdapter;
    private ItemTouchHelper mTouchHelper;

    private List<Channel> mDatas;

    private int selectCount;
    private int unselectCount;

    private OnChannelListener mOnChannelListener;

    public void setOnChannelListener(OnChannelListener onChannelListener) {
        mOnChannelListener = onChannelListener;
    }

    public static ChannelDialogFragment newInstance(List<Channel> selectedDatas, List<Channel> unselectedDatas) {
        ChannelDialogFragment dialogFragment = new ChannelDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(DATA_SELECTED, (Serializable) selectedDatas);
        bundle.putSerializable(DATA_UNSELECTED, (Serializable) unselectedDatas);
        dialogFragment.setArguments(bundle);
        return dialogFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Black_NoTitleBar);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Dialog dialog = getDialog();
        if (dialog != null) {
            dialog.getWindow().setWindowAnimations(R.style.anim_bottom_up_style);
        }
        View view = inflater.inflate(R.layout.activity_channel, null);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        Bundle bundle = getArguments();
        List<Channel> selectedDatas = (List<Channel>) bundle.getSerializable(DATA_SELECTED);
        List<Channel> unselectedDatas = (List<Channel>) bundle.getSerializable(DATA_UNSELECTED);
        setDataType(selectedDatas, Channel.TYPE_MY_CHANNEL);
        setDataType(unselectedDatas, Channel.TYPE_OTHER_CHANNEL);

        selectedDatas.get(0).setItemType(Channel.TYPE_FIXED_CHANNEL);
        selectedDatas.get(1).setItemType(Channel.TYPE_FIXED_CHANNEL);

        selectCount = selectedDatas.size();
        unselectCount = unselectedDatas.size();

        mDatas = new ArrayList<>();
        mDatas.add(new Channel(Channel.TYPE_MY_TITLE, "我的频道", 0));
        mDatas.addAll(selectedDatas);

        mDatas.add(new Channel(Channel.TYPE_OTHER_TITLE, "推荐频道", 0));
        mDatas.addAll(unselectedDatas);

        mAdapter = new ChannelAdapter(getContext());
        mAdapter.setDatas(mDatas);

        mRecyclerView.setAdapter(mAdapter);
        GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 4);
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                int itemViewType = mAdapter.getItem(position).getItemType();
                return itemViewType == Channel.TYPE_MY_TITLE || itemViewType == Channel.TYPE_OTHER_TITLE ? 4 : 1;
            }
        });
        mRecyclerView.setLayoutManager(layoutManager);

        ItemDragHelperCallBack callBack = new ItemDragHelperCallBack();
        mTouchHelper = new ItemTouchHelper(callBack);
        mTouchHelper.attachToRecyclerView(mRecyclerView);
    }

    private void setDataType(List<Channel> datas, int itemType) {
        for (Channel channel : datas) {
            channel.setItemType(itemType);
        }
    }

    @OnClick(R.id.actionbar_back)
    public void onClick(View v) {
        dismiss();
    }

    private DialogInterface.OnDismissListener mOnDismissListener;

    public void setOnDismissListener(DialogInterface.OnDismissListener onDismissListener) {
        mOnDismissListener = onDismissListener;
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        if (mOnDismissListener != null)
            mOnDismissListener.onDismiss(dialog);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    class ChannelAdapter extends BaseRecyclerMultiItemAdapter<Channel> {

        public ChannelAdapter(Context context) {
            super(context, null);
            //默认没有编辑
            addItemType(Channel.TYPE_MY_TITLE, R.layout.item_channel_title);
            addItemType(Channel.TYPE_FIXED_CHANNEL, R.layout.item_channel);
            addItemType(Channel.TYPE_MY_CHANNEL, R.layout.item_channel);
            addItemType(Channel.TYPE_OTHER_TITLE, R.layout.item_channel_title);
            addItemType(Channel.TYPE_OTHER_CHANNEL, R.layout.item_channel);
        }

        @Override
        protected void setMultiData(ViewHolderHelper viewHolderHelper, int i, Channel channel) {
            viewHolderHelper.setText(R.id.channel_name, channel.Title);
            switch (channel.getItemType()) {
                case Channel.TYPE_MY_TITLE:
                    //我的频道
                    viewHolderHelper.setText(R.id.channel_hint, "拖动调整顺序");
                    break;
                case Channel.TYPE_FIXED_CHANNEL:
                    if (channel.Title.equals("关注")) {
                        viewHolderHelper.setTextColorRes(R.id.channel_name, R.color.colorGray);
                        viewHolderHelper.setVisibility(R.id.channel_action, View.GONE);
                    } else if (channel.Title.equals("推荐")) {
                        viewHolderHelper.setTextColorRes(R.id.channel_name, R.color.colorTheme);
                        viewHolderHelper.setVisibility(R.id.channel_action, View.GONE);
                    }
                    break;
                case Channel.TYPE_MY_CHANNEL:
                    viewHolderHelper.setTextColorRes(R.id.channel_name, R.color.colorDark);
                    viewHolderHelper.setImageResource(R.id.channel_action, R.drawable.delete_o);
                    viewHolderHelper.setVisibility(R.id.channel_action, View.VISIBLE);
                    viewHolderHelper.setItemChildClickListener(R.id.channel_action);
                    viewHolderHelper.setOnItemChildClickListener(new OnItemChildClickListener() {
                        @Override
                        public void onItemChildClick(View view, int i) {
                            Channel channel = mAdapter.getItem(i);
                            selectCount--;
                            unselectCount++;
                            mAdapter.getDatas().remove(i);
                            channel.setItemType(Channel.TYPE_OTHER_CHANNEL);
                            mAdapter.addData(mAdapter.getDataCount(), channel);

                            if (mOnChannelListener != null) {
                                mOnChannelListener.onMoveToOtherChannel(i - 1, unselectCount - 1);
                            }
                        }
                    });
                    break;
                case Channel.TYPE_OTHER_TITLE:
                    //频道推荐
                    viewHolderHelper.setText(R.id.channel_hint, "点击添加频道");
                    break;
                case Channel.TYPE_OTHER_CHANNEL:
                    viewHolderHelper.setTextColorRes(R.id.channel_name, R.color.colorDark);
                    viewHolderHelper.setImageResource(R.id.channel_action, R.drawable.add_o);
                    viewHolderHelper.setVisibility(R.id.channel_action, View.VISIBLE);
                    viewHolderHelper.setItemChildClickListener(R.id.channel_action);
                    viewHolderHelper.setOnItemChildClickListener(new OnItemChildClickListener() {
                        @Override
                        public void onItemChildClick(View view, int i) {
                            Channel channel = mAdapter.getItem(i);
                            selectCount++;
                            unselectCount--;
                            mAdapter.getDatas().remove(i);
                            channel.setItemType(Channel.TYPE_MY_CHANNEL);
                            mAdapter.addData(selectCount, channel);

                            if (mOnChannelListener != null) {
                                mOnChannelListener.onMoveToMyChannel(i - selectCount - 1, selectCount - 1);
                            }
                        }
                    });
                    break;
            }
        }
    }

    class ItemDragHelperCallBack extends ItemTouchHelper.Callback {

        @Override
        public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
            int dragFlags;
            if (manager instanceof GridLayoutManager || manager instanceof StaggeredGridLayoutManager) {
                dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
            } else {
                dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
            }
            return makeMovementFlags(dragFlags, 0);
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            int startType = viewHolder.getItemViewType();
            int toType = target.getItemViewType();
            Logger.e("startType:" + startType + " toType:" + toType);
            if (startType != toType || (startType != Channel.TYPE_MY_CHANNEL && startType != Channel.TYPE_OTHER_CHANNEL)) {
                return false;
            }

            // 不同Type之间不可移动
//            if (viewHolder.getItemViewType() != target.getItemViewType() || viewHolder.getItemViewType() != Channel.TYPE_MY_CHANNEL || viewHolder.getItemViewType() != Channel.TYPE_OTHER_CHANNEL) {
//                return false;
//            }
//            onItemMove(viewHolder.getAdapterPosition(), target.getAdapterPosition());
//            return true;

            //得到当拖拽的viewHolder的Position
            int fromPosition = viewHolder.getAdapterPosition();
            //拿到当前拖拽到的item的viewHolder
            int toPosition = target.getAdapterPosition();
            Logger.e("fromPosition:" + fromPosition + " toPosition:" + toPosition);
            if (fromPosition < toPosition) {
                for (int i = fromPosition; i < toPosition; i++) {
                    Collections.swap(mAdapter.getDatas(), i, i + 1);
                }
            } else {
                for (int i = fromPosition; i > toPosition; i--) {
                    Collections.swap(mAdapter.getDatas(), i, i - 1);
                }
            }
            mAdapter.notifyItemMoved(fromPosition, toPosition);

            if (mOnChannelListener != null) {
                if (startType == Channel.TYPE_MY_CHANNEL) {
                    fromPosition--;
                    toPosition--;
                } else {
                    fromPosition = fromPosition - selectCount - 2;
                    toPosition = toPosition - selectCount - 2;
                }
                mOnChannelListener.onItemMove(startType, fromPosition, toPosition);
            }

            return true;
        }

        /**
         * 长按选中Item的时候开始调用
         *
         * @param viewHolder
         * @param actionState
         */
        @Override
        public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
            if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
                viewHolder.itemView.setBackgroundColor(Color.LTGRAY);
            }
            super.onSelectedChanged(viewHolder, actionState);
        }

        /**
         * 手指松开的时候还原
         *
         * @param recyclerView
         * @param viewHolder
         */
        @Override
        public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            super.clearView(recyclerView, viewHolder);
            viewHolder.itemView.setBackgroundColor(0);
        }

        @Override
        public boolean isItemViewSwipeEnabled() {
            return false; // 不需要侧滑
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        }

    }

    public interface OnChannelListener {

        void onItemMove(int itemType, int starPos, int endPos);

        void onMoveToMyChannel(int starPos, int endPos);

        void onMoveToOtherChannel(int starPos, int endPos);
    }

}
